# coding=utf-8
import json
import decimal

import time
from django.db import transaction
from django.db.models import F

from worldcup.apps.userModel.models import ShoppingCart,Sku
from worldcup.commons.CommonResult import rest, CommonResult




@transaction.atomic
def add_shopcart(openid, sku_code, qty):
	count = ShoppingCart.objects.filter(openid=openid, sku_code=sku_code).count()
	if count == 0:  # 购物车没有此商品，插入
		if qty <= 0:
			return
		sku_to_cart = ShoppingCart(openid=openid, sku_code=sku_code, qty=qty)
		sku = Sku.objects.get(sku_code=sku_code)
		sku_to_cart.sku_name = sku.sku_name
		sku_to_cart.sku_image = sku.sku_images
		sku_to_cart.sku_specification = sku.sku_specification
		sku_to_cart.origin_price = sku.origin_price
		sku_to_cart.add_price = sku.price
		sku_to_cart.created_at = int(time.time())
		sku_to_cart.updated_at = int(time.time())
		sku_to_cart.save()
	else:  # 购物车有商品，更改数量
		ShoppingCart.objects.filter(openid=openid, sku_code=sku_code).update(qty=F('qty') + qty,
																				  updated_at=int(time.time()))
		sku = ShoppingCart.objects.values("qty").filter(openid=openid, sku_code=sku_code).get()
		if sku["qty"] == 0:  # 更新后数量为0,删除
			ShoppingCart.objects.filter(openid=openid, sku_code=sku_code).delete()


@rest
def get_shopcart_num(request):
	openid = request.GET.get("openid")
	if openid is None:
		return CommonResult(-1, "openid为空")
	shopcart_sku_list = ShoppingCart.objects.values("qty").filter(openid=openid).all()
	result = 0
	for sku in shopcart_sku_list:
		qty = sku.get("qty")
		result = result + qty
	return CommonResult(0, result)



@rest
def shopcart_sku_list(request):
	user_openid = request.GET.get('openid')
	skus = ShoppingCart.objects.filter(openid=user_openid)

	account = decimal.Decimal('0')#总价格
	sku_reuslts = []
	for sku in skus:
		current_price = Sku.objects.get(sku_code=sku.sku_code).price
		current_price = decimal.Decimal(current_price)
		account = account + current_price * decimal.Decimal(sku.qty)
		result = {
			"openid": sku.openid,
			"sku_code": sku.sku_code,
			"sku_name": sku.sku_name,
			"sku_image": sku.sku_image,
			"sku_specification":sku.sku_specification,
			"origin_price": str(sku.origin_price),
			"add_price": str(sku.add_price),
			"qty":sku.qty,
			"current_price": str(current_price),
			"created_at":sku.created_at,
			"updated_at":sku.updated_at
		}
		sku_reuslts.append(result)
	results = {
		"totalAccount": str(account),
		"skus": sku_reuslts
	}
	return CommonResult(0, results)


@transaction.atomic
@rest
def add_sku_to_shopcart(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	user_openid = reqest_params.get('openid')
	sku_code = reqest_params.get('skuCode')
	qty = reqest_params.get('qty')

	add_shopcart(user_openid, sku_code, qty)

	# 计算最新价格（按加车价格算）
	skus = ShoppingCart.objects.values("add_price", "qty").filter(openid=user_openid).all()
	account = decimal.Decimal('0')  # 总价格
	for sku in skus:
		account = account + sku["add_price"] * decimal.Decimal(str(sku["qty"]))
	return CommonResult(0, {"totalAccount": str(account)})



@transaction.atomic
@rest
def delete_shopcart(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	user_openid = reqest_params.get('openid')
	request_skus = reqest_params.get('skus')
	for sku in request_skus:
		ShoppingCart.objects.filter(openid=user_openid, sku_code=sku).delete()

	# 计算总价格
	# 计算最新价格（按加车价格算）
	skus = ShoppingCart.objects.values("add_price", "qty").filter(openid=user_openid).all()
	account = decimal.Decimal('0')  # 总价格
	for sku in skus:
		account = account + sku["add_price"] * decimal.Decimal(str(sku["qty"]))
	return CommonResult(0, {"totalAccount": str(account)})




@transaction.atomic
@rest
def batch_add_sku_to_shopcart(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	user_openid = reqest_params.get('openid')
	request_skus = reqest_params.get('skus')
	for request_sku in request_skus:
		sku_code = request_sku.get('skuCode')
		qty = request_sku.get('qty')

		add_shopcart(user_openid, sku_code, qty)

	# 计算最新价格（按加车价格算）
	skus = ShoppingCart.objects.values("add_price", "qty").filter(openid=user_openid).all()
	account = decimal.Decimal('0')  # 总价格
	for sku in skus:
		account = account + sku["add_price"] * decimal.Decimal(str(sku["qty"]))
	return CommonResult(0, {"totalAccount": str(account)})
